package com.example.hzit.service.impl;

import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileService {

    private final String uploadDir = "static/images"; // 图片存储路径

    public String uploadFile(MultipartFile file) {
        try {
            // 确保目录存在
            Path directoryPath = Paths.get(uploadDir);
            Files.createDirectories(directoryPath);

            // 获取文件原始名称
            String originalFileName = file.getOriginalFilename();
            // 生成一个唯一的文件名，防止文件重名
            String newFileName = UUID.randomUUID().toString() + "_" + originalFileName;

            // 保存文件到指定目录
            Path destinationPath = directoryPath.resolve(newFileName);
            file.transferTo(destinationPath.toFile());

            // 返回保存后的文件相对路径，前端可以根据这个路径访问图片
            return "/" + uploadDir + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
